package com.jtlrm.ckd.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.base.sdk.base.net.CommonObserver;
import com.base.sdk.util.CommonUtil;
import com.base.sdk.util.DateFormatUtil;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.TitleBarActivity;
import com.jtlrm.ckd.entity.ShengHuaZhiBiaoEntity;
import com.jtlrm.ckd.entity.event.ShengHuaUpdateMessage;
import com.jtlrm.ckd.entity.submitEntity.ShengHuaSubmitData;
import com.jtlrm.ckd.entity.submitEntity.ShengHuaSubmitSubData;
import com.jtlrm.ckd.mvp.model.ShengHuaModel;
import com.jtlrm.ckd.mvp.view.adapter.ShengHuaDetailAdapter;
import com.jtlrm.ckd.util.EventBusUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

public class ShengHuaCheckDetailActivity extends TitleBarActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    ShengHuaDetailAdapter adapter;
    ShengHuaModel shengHuaModel;
    boolean isAdd = false; // 是否是新增数据
    TextView seletcT;
    ImageView iconI;
    TimePickerView timePickerView;
    String currentTime = ""; // 当前选中的时间
    String patientId;
    String treatmentId;
    boolean dateIsRight = false;
    String errorMsg;

    public static void goDetail(Context context, boolean isAdd, String patientId) {
        Intent intent = new Intent(context, ShengHuaCheckDetailActivity.class);
        intent.putExtra("isAdd", isAdd);
        intent.putExtra("patientId", patientId);
        context.startActivity(intent);
    }

    public static void goDetail(Context context, boolean isAdd, String patientId, String treatmentId, String currentTime) {
        Intent intent = new Intent(context, ShengHuaCheckDetailActivity.class);
        intent.putExtra("isAdd", isAdd);
        intent.putExtra("patientId", patientId);
        intent.putExtra("treatmentId", treatmentId);
        intent.putExtra("currentTime", currentTime);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isAdd = getIntent().getBooleanExtra("isAdd", false);
        patientId = getIntent().getStringExtra("patientId");
        treatmentId = getIntent().getStringExtra("treatmentId");
        currentTime = getIntent().getStringExtra("currentTime");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected String getTitleText() {
        if (isAdd) {
            return "新增数据";
        } else {
            return "生化数据";
        }
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_sheng_hua_check_detail);
    }

    @Override
    protected void initView() {
        shengHuaModel = new ShengHuaModel();
        adapter = new ShengHuaDetailAdapter(isAdd);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapter);
        View header = LayoutInflater.from(context).inflate(R.layout.shenghua_detail_header, recyclerView, false);
        seletcT = header.findViewById(R.id.date);
        iconI = header.findViewById(R.id.icon);
        if (isAdd) {
            iconI.setVisibility(View.VISIBLE);
            seletcT.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonUtil.hideSoftInput(context, seletcT);
                    if (timePickerView != null) {
                        timePickerView.show();
                    }
                }
            });
            timePickerView = new TimePickerBuilder(context, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    currentTime = DateFormatUtil.dateFormatLine(date.getTime());
                    setText(seletcT, currentTime);
                    checkRiQi();
                }
            }).build();
            currentTime = DateFormatUtil.dateFormatLine(System.currentTimeMillis());
            setText(seletcT, currentTime);
            checkRiQi();
        } else {
            iconI.setVisibility(View.GONE);
            setText(seletcT, currentTime);
        }
        adapter.addHeaderView(header);
    }

    @Override
    protected void obtainData() {
        adapter.openLoadAnimation();
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (isAdd) {
                    loadZhiBiaoData();
                } else {
                    loadData();
                }
                smartRefreshLayout.setEnableRefresh(false);
            }
        });
        smartRefreshLayout.autoRefresh();
    }

    private void loadData() {
        shengHuaModel.queryShengHuaDataById(treatmentId, new CommonObserver<List<ShengHuaZhiBiaoEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                closeFrshorLoadmore();
            }

            @Override
            public void onResult(List<ShengHuaZhiBiaoEntity> data) {
                adapter.replaceData(data);
                closeFrshorLoadmore();
            }
        }, lifecycleSubject);
    }

    @Override
    protected void initEvent() {

    }


    private void loadZhiBiaoData() {
        shengHuaModel.queryZhiBiao(new CommonObserver<List<ShengHuaZhiBiaoEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                closeFrshorLoadmore();
            }

            @Override
            public void onResult(List<ShengHuaZhiBiaoEntity> data) {
                adapter.replaceData(data);
                closeFrshorLoadmore();
            }
        }, lifecycleSubject);
    }


    @Override
    protected void initTitleBar() {
        super.initTitleBar();
        if (isAdd) {
            titleBar.tvRight.setText("完成提交");
            titleBar.tvRight.setVisibility(View.VISIBLE);
            titleBar.tvRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dateIsRight) {
                        submit();
                    } else {
                        showToast(notEmpty(errorMsg) ? errorMsg : "该天已存在记录");
                    }
                }
            });
        }
    }

    private void checkRiQi() {
        if (isAdd) {
            shengHuaModel.checkShengHuaRiQi(patientId, currentTime, new CommonObserver<String>() {
                @Override
                public void onError(int errType, String errMessage) {
                    showToast(errMessage);
                    errorMsg = errMessage;
                    dateIsRight = false;
                }

                @Override
                public void onResult(String data) {
                    dateIsRight = true;
                }
            }, lifecycleSubject);
        }
    }

    private void submit() {
        List<ShengHuaZhiBiaoEntity> list = adapter.getData();
        ShengHuaSubmitData submitData = new ShengHuaSubmitData();
        submitData.setPatientId(patientId);
        submitData.setMeasureDate(currentTime);
        List<ShengHuaSubmitSubData> submitSubData = new ArrayList<>();
        boolean hasValue = false;
        String shuzhangya = "";
        String sousuoya = "";
        for (ShengHuaZhiBiaoEntity entity : list) {
            ShengHuaSubmitSubData data = new ShengHuaSubmitSubData();
            data.setId(entity.getId());
            data.setValue(entity.getValue());
            submitSubData.add(data);
            if (!hasValue && notEmpty(entity.getValue())) {
                hasValue = true;
            }
            if ("1".equals(entity.getSort())) {
                shuzhangya = entity.getValue();
            }
            if ("2".equals(entity.getSort())) {
                sousuoya = entity.getValue();
            }
        }
        if (!hasValue) {
            showToast("请至少填写一项或多项检查指标数据");
            return;
        }
        if (notEmpty(sousuoya) != notEmpty(shuzhangya)) {
            showToast("收缩压和舒张压必须一起填写");
            return;
        }
        submitData.setInspectrecords(submitSubData);
        showLoadingDialog("提交中");
        shengHuaModel.submitData(submitData, new CommonObserver<String>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(String data) {
                showToast("提交成功");
                EventBusUtil.postEvent(new ShengHuaUpdateMessage());
                dismissLoadingDialog();
                finish();
            }
        }, lifecycleSubject);
    }

    /**
     * 关闭加载更多或者刷新
     */
    private void closeFrshorLoadmore() {
        if (smartRefreshLayout.isLoading()) {
            smartRefreshLayout.finishLoadmore();
        }
        if (smartRefreshLayout.isRefreshing()) {
            smartRefreshLayout.finishRefresh();
        }
    }

}
